/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp.net;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import dk.redia.lib.log.Log;
import android.widget.Toast;
import dk.redia.lib.utils.AppApplication;
import dk.redia.lib.utils.AppConfiguration;
import dk.redia.lib.xmlrpc.XmlRpcClientResultListener;
import dk.redia.lib.xmlrpc.XmlRpcResultDumper;
import dk.redia.lib.xmlrpc.XmlRpcResultUtils;
import dk.redia.libraryapp.R;
import dk.redia.libraryapp.model.Loan;
import dk.redia.libraryapp.xmlrpc.library.XmlRpcClient;

public class LoansRemoteListManager extends RemoteListManager<Loan> {

	public static final String EXTRA_RESULT_DATA_RESERVABLE_COUNT = "reservableCount";
	private static final String logTag = "LoansRemoveListManager";
	private Set<Integer> renewableIndices = new HashSet<Integer>();
	
	@Override
	public void loadListChunk(final int offset, final int count) {
		XmlRpcClient.getInstance().getLoans(AppConfiguration.getInstance().getCustomerId(), AppConfiguration.getInstance().getApiKey(), count, offset, new XmlRpcClientResultListener() {
			
			public void callFailed(String message) {
				Log.e(LoansRemoteListManager.logTag, "Failed to load loans: " + message);
				AppApplication.toast(R.string.failedToGetLoansText, Toast.LENGTH_LONG);
			}
			
			public void callCompleted(Object resultObj) {
				XmlRpcResultDumper.dump(resultObj);
				List<Loan> resultLoans = new ArrayList<Loan>();
				Map<String, Object> result = XmlRpcResultUtils.unpackStandardResult(resultObj);
				if (result==null) {
					chunkLoadFailed(offset, count, AppApplication.getAppContext().getResources().getString(R.string.failedToGetLoansText));
					return;
				}
				Map<String, Object> data = XmlRpcResultUtils.unpackStruct(result.get("data"));
				if (data==null) {
					chunkLoadFailed(offset, count, AppApplication.getAppContext().getResources().getString(R.string.failedToGetLoansText));
					return;
				}
				Object[] loansArr = XmlRpcResultUtils.unpackArray(data.get("data"));
				if (loansArr!=null) {
					Integer resultCount = (Integer)data.get("totalCount");
					int i=0;
					for (Object loanObj : loansArr) {
						Map<String, Object> loanMap = XmlRpcResultUtils.unpackStruct(loanObj);
						Loan loan = new Loan();
						loan.setAuthor((String)loanMap.get("author"));
						loan.setLoanIsRenewable((Boolean)loanMap.get("loanIsRenewable"));
						loan.setTitle((String)loanMap.get("title"));
						loan.setLoanDate(new Date(1000L*(Integer)loanMap.get("loanDate")));
						loan.setLoanDueDate(new Date(1000L*(Integer)loanMap.get("loanDueDate")));
						loan.setLoanId((String)loanMap.get("loanId"));
						
						// Keep track of whether we have any renewable loans
						// This is needed by the UI to determine if we should enable
						// "Renew all" functionality.
						int index = offset + i++;
						
						if (loan.getLoanIsRenewable()) {
							renewableIndices.add(index);
						} else {
							renewableIndices.remove(index);
						}
						
						resultLoans.add(loan);
					}
					chunkLoaded(offset, resultCount, resultLoans);
					setExtraResultData(EXTRA_RESULT_DATA_RESERVABLE_COUNT, renewableIndices.size());
				} else {
					chunkLoadFailed(offset, count, AppApplication.getAppContext().getResources().getString(R.string.failedToGetLoansText));
					return;
				}
			}
		});
	}
}
